package com.enqualcomm.kids.activities;

import android.content.Intent;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.VideoView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.component.DownloadAppIntentService;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.mvp.oscard.OscardAdapter;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.GetProductUrlParams;
import com.enqualcomm.kids.network.socket.request.OscardProductsParams;
import com.enqualcomm.kids.network.socket.response.GetProductUrlResult;
import com.enqualcomm.kids.network.socket.response.OscardProductsResult;
import com.enqualcomm.kids.network.socket.response.QueryUserTerminalInfoResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.enqualcomm.kids.view.RecyclerItemClickListener;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.util.List;

import common.utils.DensityUtil;
import common.utils.PlatformUtil;
import de.greenrobot.event.EventBus;

@EActivity(R.layout.activity_oscard)
public class OscardActivity extends BaseActivity {
    private static final String OSCARD_PKN = "com.askjt";
    @ViewById(R.id.recyclerview)
    RecyclerView recyclerview;
    @ViewById(R.id.tabLayout)
    TabLayout tabLayout;
    @ViewById(R.id.download_btn)
    Button download_btn;
    @ViewById(R.id.videowiew)
    VideoView videowiew;
    @Extra("terminal")
    TerminallistResult.Terminal terminal;
    OscardAdapter adapter;
    AppDefault appDefault;
    NetworkModel networkModel;
    List<OscardProductsResult.Data> list;
    OscardProductsResult.Data selectedItem;
    OscardProductsResult.Product selectedProduct;
    int itemOffset;
    String appDownloadUrl;
    boolean oscardAppInstalled;

    @AfterViews
    void afterViews(){
        itemOffset = DensityUtil.dip2px(this, 6);
        appDefault = new AppDefault();
        networkModel = new NetworkModel();
        QueryUserTerminalInfoResult.Data info = new UserTerminalDefault(terminal.userterminalid).getInfo();
        setupTitleIcon(info, terminal.terminalid, terminal.userterminalid,"AR学堂");
        initView();
        initData();
        //获取奥狮卡下载地址
        getOscardDownloadUrl();
        EventBus.getDefault().register(this);
    }

    public void onEvent(OscardProductsResult.Product product) {
        selectedProduct.ifbuy = product.ifbuy;
        selectedProduct.orderid = product.orderid;
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 重新判断是否已安装奥狮卡app
        initDownloadButton();
    }

    private void initDownloadButton() {
        //如果已安装奥狮卡，点击自动打开，如果没有安装，点击开始安装
        if (PlatformUtil.isAvilible(this,OSCARD_PKN)) {
            oscardAppInstalled = true;
            download_btn.setText("打开奥狮卡APP");
            download_btn.setBackgroundResource(R.drawable.oscard_pay_btn);
        }else {
            oscardAppInstalled = false;
            download_btn.setText("下载奥狮卡");
            download_btn.setBackgroundResource(R.drawable.oscard_download_btn);
        }
    }

    private void initData() {
        OscardProductsParams params = new OscardProductsParams(appDefault.getUserkey(), appDefault.getUserid(), terminal.terminalid);
        networkModel.loadDataFromServer(new SocketRequest<OscardProductsResult>(params, new NetworkListener<OscardProductsResult>() {
            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(OscardProductsResult response) {
                if (response.code==0){
                    list = response.result;

                    if (list!=null&&!list.isEmpty()){
                        tabLayout.removeAllTabs();
                        for (OscardProductsResult.Data data : list) {
                            tabLayout.addTab(tabLayout.newTab().setText(data.productname));
                        }

                        fillData(0);
                    }
                }
            }
        }));
    }

    private void initView() {
        //1.点击tab，切换recyclerview的数据
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab){
                fillData(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        //2.点击recyclerview，打开二级页面
        recyclerview.setHasFixedSize(true);
        recyclerview.setLayoutManager(new GridLayoutManager(this,3));
        recyclerview.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
                int i = itemPosition % 3;
                if (i==0) {//左边
                    outRect.set(0,itemOffset,itemOffset,0);
                }else if (i==1){//中间
                    outRect.set(itemOffset,itemOffset,itemOffset,0);
                }else {//右边
                    outRect.set(itemOffset,itemOffset,0,0);
                }
            }
        });
        adapter = new OscardAdapter(getLayoutInflater());
        recyclerview.setAdapter(adapter);
        recyclerview.addOnItemTouchListener(new RecyclerItemClickListener(this,recyclerview,new RecyclerItemClickListener.OnItemClickListener(){
            @Override
            public void onItemClick(View view, int position) {
                showOscardPictures(position);
            }

            @Override
            public void onItemLongClick(View view, int position) {
            }
        }));


        //3.奥狮卡介绍视频
//        MediaController mController = new MediaController(this);
//        videowiew.setMediaController(mController);
//        mController.setMediaPlayer(videowiew);
        String fileName = "android.resource://"+  getPackageName() + "/raw/aoshika_watchx10s1280x720";
        videowiew.setVideoURI(Uri.parse(fileName));
        videowiew.requestFocus();
        videowiew.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                video_preview_iv.setVisibility(View.VISIBLE);
            }
        });
    }

    private void getOscardDownloadUrl() {
//        networkModel.loadDataFromServer(new SocketRequest<GetProductUrlResult>(new GetProductUrlParams("1001"), new NetworkListener<GetProductUrlResult>() {
//            @Override
//            public void onError(VolleyError error) {
//            }
//
//            @Override
//            public void onSuccess(GetProductUrlResult response) {
//                if (response.code==0) {
//                    appDownloadUrl = response.getUrl();
//                }
//            }
//        }));
    }

    @ViewById(R.id.video_preview_iv)
    View video_preview_iv;

    @Click(R.id.video_preview_iv)
    void startPlay(View v){
        videowiew.start();
        video_preview_iv.setVisibility(View.INVISIBLE);
    }

    private void showOscardPictures(int position) {
        selectedProduct = selectedItem.productpay.get(position);
        Intent intent = new Intent(this, OscardShowActivity_.class);
        intent.putExtra("terminal",terminal);
        intent.putExtra("product",selectedProduct);
        startActivity(intent);
    }

    private void fillData(int position) {
        selectedItem = list.get(position);
        adapter.setData(selectedItem);
    }

    @Click(R.id.download_btn)
    void download(){
        if (oscardAppInstalled) {//已安装，打开app
            try{
                Intent launchIntentForPackage = getPackageManager().getLaunchIntentForPackage(OSCARD_PKN);
                startActivity(launchIntentForPackage);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {//未安装,下载
            Uri uri = Uri.parse("http://shouji.baidu.com/software/9838260.html");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
//            if (appDownloadUrl!=null){
//                Intent service = new Intent(getApplicationContext(), DownloadAppIntentService.class);
//                service.putExtra("url", appDownloadUrl);
//                startService(service);
//            }else {
//                getOscardDownloadUrl();
//            }
        }
    }

    @Click(R.id.title_bar_left_iv)
    void finishActivity() {
        finish();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        networkModel.onStop();
        super.onDestroy();
    }
}
